<?php
use yii\helpers\Html;
$post=\Yii::$app->session->getFlash('post');
?>

<?php $this->beginBlock('title'); ?>
    <?php if(isset($model['id'])):?>编辑<?php else:?>新增<?php endif;?>文章
<?php $this->endBlock();?>

<?php $this->beginBlock('breadcrumb'); ?>
<li><a href="<?php echo \Yii::$app->urlManager->createUrl('/article/index')?>">文章管理</a></li>
<li class="active"><a href="<?php echo \Yii::$app->urlManager->createUrl('/article/edit',['id'=>isset($model['id'])?$model['id']:0]);?>"><?php if(isset($model['id'])):?>编辑<?php else:?>新增<?php endif;?>文章</a></li>
<?php $this->endBlock();?>

<?php $this->beginBlock('css'); ?>
<link href="<?php echo Yii::$app->request->baseUrl; ?>/js/summernote/dist/summernote.css" rel="stylesheet">
<?php $this->endBlock();?>

<link rel="stylesheet" type="text/css" href="<?php echo Yii::$app->request->baseUrl; ?>/js/bootstrap-fileinput-master/css/fileinput.css" />
<style>
.auto_height { height: 350px; OVERFLOW-Y: auto; SCROLLBAR-FACE-COLOR: #ffffff; }
.show_upload { display:none; }
</style>
<div class="row">
	<div class="col-sm-12">
		<section class="panel">
			<div class="panel-body">
				<div class="form">
					<form id="article_form" class="cmxform form-horizontal tasi-form" method="post" action="<?php echo \Yii::$app->urlManager->createUrl('/article/save');?>">
						<?php if($model):?>
						<div class="form-group">
							<label for="game_name" class="control-label col-lg-2">所属游戏</label>
							<div class="col-lg-10">
                               	<input class="form-control" id="game_name" name="game_name" value="<?=Html::encode($model['game']['game_name']?:'尚未指派');?>" type="text" disabled="" />
                            </div>
						</div>
						<?php else:?>
						<div class="form-group">
							<label for="game_name" class="control-label col-lg-2">所属游戏</label>
							<div class="col-lg-10">
                               	<span id="game_name"></span><a href="#addGameModal" data-toggle="modal" class="btn btn-success">查找并添加游戏</a>
                            </div>
						</div>
						<?php endif;?>
                        <div class="form-group">
                            <label for="kind" class="control-label col-lg-2">类别</label>
                            <div class="col-lg-10">
                                <div class="radio-custom radio-success">
		                            <input type="radio" value="1" <?php if(isset($post['kind']) && $post['kind']==1):?>checked<?php elseif(isset($model['kind']) && $model['kind']==1):?>checked<?php endif;?> name="kind" id="kind1">
		                            <label for="kind1">新闻</label>
		                            <input type="radio" value="2" <?php if(isset($post['kind']) && $post['kind']==2):?>checked<?php elseif(isset($model['kind']) && $model['kind']==2):?>checked<?php endif;?> name="kind" id="kind2">
		                            <label for="kind2">活动</label>
		                        </div>
                            </div>
                        </div>
						<div class="form-group">
                            <label for="title" class="control-label col-lg-2">标题</label>
                            <div class="col-lg-10">
                                <input class="form-control " id="title" type="text" value="<?php if(isset($post['title'])){ echo $post['title'];}else{ echo Html::encode($model['title']?:''); }?>" name="title" required />
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="author" class="control-label col-lg-2">作者</label>
                            <div class="col-lg-10">
                                <input class="form-control " id="author" type="text" value="<?php if(isset($post['author'])){ echo $post['author'];}else{ echo Html::encode($model['author']?:''); }?>" name="author" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="content" class="control-label col-lg-2">内容</label>
                            <div class="col-lg-10">
                           		<div class="summernote"><?php if(isset($post['content'])){echo $post['content']; }else{ echo Html::encode($model['content']?:''); }?></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="number" class="control-label col-lg-2">Logo图片</label>
                            <div class="col-lg-10">
                            	<?php if(isset($model['logo_path'])):?>
	                            	<span class="file-input">
	                            		<div class="file-preview">
	                            			<div class="close fileinput-remove">×</div>
	                            			<div class="">
	                            				<div class="file-preview-thumbnails">
													<div data-fileindex="0" class="file-preview-frame">
	   													<img style="width:auto;height:160px;" alt="<?php echo isset($model['game_name'])?$model['game_name']:'';?>" title="<?php echo isset($model['game_name'])?$model['game_name']:'';?>" class="file-preview-image" src="<?=filepath($model['logo_path']);?>">
	   													<div class="file-thumbnail-footer">
	    													<div style="width: 170px;" class="file-caption-name" title="<?php echo isset($model['game_name'])?$model['game_name']:'';?>"><?php echo isset($model['game_name'])?$model['game_name']:'';?></div>
														</div>
													</div>
												</div>
												<div class="clearfix"></div>
											</div>
										</div>
									</span>
									<div class="show_upload">
										<input id="file_logo_path" class="file" type="file" name="file" multiple=true>
			                        	<span class="help-block">请上传[jpg、png、gif]格式的图片，建议规格为500*500，不大于1M </span>
									</div>
                            	<?php else:?>
                            		<input id="file_logo_path" class="file" type="file" name="file" multiple=true>
		                        	<span class="help-block">请上传[jpg、png、gif]格式的图片，建议规格为500*500，不大于1M </span>
		                        <?php endif;?>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sort" class="control-label col-lg-2">排序值</label>
                            <div class="col-lg-10">
                                <input class="form-control " id="sort" type="text" value="<?php if(isset($post['sort'])){ echo $post['sort'];}else{ echo Html::encode($model['sort']?:0); }?>" name="sort" />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-lg-offset-2 col-lg-10">
                                <input type="hidden" name="_csrf" id="_csrf" value="<?=\Yii::$app->request->csrfToken; ?>" />
        						<?php if(isset($model['id'])):?><input type="hidden" name="id" value="<?=$model['id'];?>" /><?php endif;?>
                                <input type="hidden" name="game_id" id="game_id" value="<?php if($model){ echo $model['game_id'];}else{echo '0';}?>" />
                                <input type="hidden" name="content" id="content" value="" />
                                <input type="hidden" value="<?php echo isset($model['logo_path'])?$model['logo_path']:'';?>" id="logo_path" name="logo_path" />
                                <button class="btn btn-success" type="submit" id="savebtn"> 保存</button>
                                <button class="btn btn-default" type="button" onclick="javascript:history.go(-1)"> 取消</button>
                            </div>
                        </div>
                    </form>
                </div>
			</div>
		</section>
	</div>
</div>
<!-- Modal -->
<div class="modal fade" id="addGameModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">添加所属游戏</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-sm-12">
						<section class="panel">
							<div class="panel-body">
								<form class="form-inline" role="form" id="game_search_form">
									<div class="form-group">
										<label class="sr-only" for="key">关键字</label>
				                        <input type="text" class="form-control" id="modal_key" name="modal_key" value="" placeholder="游戏名称">
				                    </div>
				                    <div class="form-group">
				                    	<select class="form-control" name="state_id">
											<option value="" <?php if(\Yii::$app->request->get('state_id')!=''):?>selected<?php endif;?>>--所有状态--</option>
                                            <?php foreach($states as $item):?>
                								<option value="<?=$item['state_id'];?>" <?php if($item['state_id']==\Yii::$app->request->get('state_id')):?>selected<?php endif;?>><?=$item['state_name'];?></option>
                							<?php endforeach;?>
										</select>
				                    </div>
									<button type="button" class="btn btn-info" id="GameFind"><i class="fa fa-search"></i> 查询</button>
								</form>
							</div>
							<div id="GameList">

							</div>
						</section>
					</div>
                </div>
            </div>
            <div class="modal-footer" style="display:none;">
                <button data-dismiss="modal" class="btn btn-default" type="button" id="closeModel">Close</button>
            </div>
        </div>
    </div>
</div>
<!-- modal -->
<?php
$this->beginBlock('script');
?>
<script type="text/javascript" src="<?php echo Yii::$app->request->baseUrl; ?>/js/bootstrap-fileinput-master/js/fileinput.js"></script>
<script type="text/javascript" src="<?php echo Yii::$app->request->baseUrl; ?>/js/summernote/dist/summernote.min.js"></script>
<script type="text/javascript">
//约束上传图片条件
$("#file_logo_path").fileinput({
    allowedFileExtensions : ['jpg', 'png','gif'],
    showPreview : true,
    maxFileSize: 1000,
    minImageWidth: 500,
    minImageHeight: 500,
    showUpload:false,
    //maxFilesNum: 1,
});

$(function() {
	//开始上传图片
    $(document).on('change', "#file_logo_path", function() {
    	var csrfToken = $('meta[name="csrf-token"]').attr("content");
        $.ajaxFileUpload({
            url : "<?php echo \Yii::$app->urlManager->createUrl('/storage/upload')?>",
            secureuri : false,
            fileElementId : 'file_logo_path',
            dataType : 'json',
            data : { _csrf:csrfToken },
            success : function (data, status) {
                $("#logo_path").val(data.path);
            },
            error : function (data, status, e) {
                alert(e);
            }
        });
    });
});

//修改图片时，关闭图片显示改为上传
$(".fileinput-remove").click(function(){
	$(".file-input").toggle();
	$("#logo_path").val("");
	$(".show_upload").show();
	$(".file-input-new").show();
});

//游戏模态框的搜索
$("#GameFind").click(function() {
    $.get("<?php echo \Yii::$app->urlManager->createUrl('/game/search-by-beta');?>", $("#game_search_form").serialize(), function(data) {
        $("#GameList").html(data);
    },'html');
    $("#GameList").addClass("auto_height");
});

function assignGame(game_id,game_name){
	if(game_id>0 && game_name!=''){
		$("#game_name").text(game_name);
		$("#game_id").val(game_id);
		//关闭模态框
		$("#closeModel").trigger("click");
	}else{
	    alert("指派失败，参数错误");
	    return false;
	}
}

jQuery(document).ready(function(){
	$('.summernote').summernote({
        height: 200,                 // set editor height
        minHeight: null,             // set minimum height of editor
        maxHeight: null,             // set maximum height of editor
        focus: false,                 // set focus to editable area after initializing summernote
        onImageUpload: function(files, editor, $editable) {   //上传图片
			var file=files[0];
			var filename = false;
			try{
				filename = file['name'];
			} catch(e){
				filename = false;
			}
			if(!filename){
				alert("文件获取失败");
			}
			data = new FormData();
			data.append("file", file);
			var csrfToken = $('meta[name="csrf-token"]').attr("content");
			var img_base_url="<?=Yii::$app->params['filePath'];?>";
			data.append("_csrf", csrfToken);
			$.ajax({
				data: data,
				dataType : 'json',
				type: "POST",
				url: "<?php echo \Yii::$app->urlManager->createUrl('/storage/upload')?>",
				cache: false,
				contentType: false,
				processData: false,
				success: function(data) {
					editor.insertImage($editable, img_base_url+data.path);
				},
				error:function(){
					alert("上传失败");
				}
			});
		}
    });

	$("#savebtn").click(function(){
		$("#content").val($('.summernote').eq(0).code());
		$("#article_form").submit();
	});
});
</script>
<?php $this->endBlock('script');?>